import datetime

from django.shortcuts import render_to_response, get_object_or_404
from django.newforms import form_for_instance, form_for_model
from django import newforms as forms
from django.http import HttpResponseRedirect
from models import VMTYPE_CHOICES, VMCOPYMODE_CHOICES, BACKUP_START_METHOD_CHOICES, JOBMODE_CHOICES, HOURS_CHOICES, RECOVER_CHOICES
from models import VMOSGUEST_CHOICES, VMHOST, VM, Log, OVIMSettings, LocalStorage
from models import BackupJobPool, Jobs

class VMHOSTForm(forms.Form):
    name = forms.CharField(max_length=80, label='Name')
    comments = forms.CharField(required=False, max_length=100, widget=forms.Textarea, label='Comments', help_text='A good place to put the Host description ie: bi-xeon 1,4Ghz, etc...')
    ipaddress = forms.CharField(max_length=80, label='IP', help_text='IP Address or DNS Name of the Host')
    type = forms.CharField(max_length=10, widget=forms.Select(choices=VMTYPE_CHOICES), label='Type')
    copyMode = forms.CharField(max_length=3, widget=forms.Select(choices=VMCOPYMODE_CHOICES), label='Copy Method')
    NFSRootPath = forms.CharField(max_length=254, label='NFS Mount Point', help_text='Enter the root path of the mounted NFS server without the trailing slash')    
    vm_root_path = forms.CharField(max_length=254, label="VMs Root Path")
    backup_storage = forms.ModelChoiceField(queryset=LocalStorage.objects.all())


class VMForm(forms.Form):
    name = forms.CharField(max_length=80, label='Name')
    path = forms.CharField(max_length=254, label='Root Path', help_text='The base path of vm without the trailing slash')
    configFileName = forms.CharField(max_length=80, label='Config File', help_text='the active vmx file that describe the VM')
    osguest = forms.CharField(max_length=20, widget=forms.Select(choices=VMOSGUEST_CHOICES), label='OS')
    

class JobPoolForm(forms.Form):
    name = forms.CharField(max_length=80, label='Name')
    backupmode = forms.CharField(max_length=8, widget=forms.Select(choices=JOBMODE_CHOICES), label='Backup Method')
    startmethod = forms.CharField(max_length=3, widget=forms.Select(choices=BACKUP_START_METHOD_CHOICES), label='When')
    startat = forms.CharField(label='On', widget=forms.Select(choices=HOURS_CHOICES), help_text='Enter an hour' )
    timeoutH = forms.IntegerField(min_value=1, max_value=20, label='TimeOut (Hours)')
    vmlist = forms.ModelMultipleChoiceField(queryset=VM.objects.order_by('name'))

class VMRecoverForm(forms.Form):    
    recover_mode = forms.CharField(max_length=3, widget=forms.Select(choices=RECOVER_CHOICES))
    from_store = forms.ModelChoiceField(queryset=LocalStorage.objects.all())
    vmhost = forms.ModelChoiceField(queryset=VMHOST.objects.order_by('name'), required=False)
    newname = forms.CharField(max_length=80, required=False)


def VMList(request, VMHost_id):
    vmHost = get_object_or_404(VMHOST, pk=VMHost_id)
    vms = vmHost.vm_set.all()
    return render_to_response('vm_list.html', { 'vmHost': vmHost, 'vms': vms, })

def VMDelete(request, VMHost_id, VM_id):
    object = get_object_or_404(VM, pk=VM_id)
    object.delete()
    return HttpResponseRedirect('/ovim/' + VMHost_id + '/listvms/')

def VMAdd(request, VMHost_id):
    vmHost = get_object_or_404(VMHOST, pk=VMHost_id)  
    form = VMForm()
    vm = None
    if request.method == 'POST':
        form = VMForm(request.POST)
        if form.is_valid():
            vm = VM(**form.cleaned_data)
            vm.vmhost = vmHost
            vm.save()
            return HttpResponseRedirect('/ovim/' + VMHost_id + '/listvms/')
        else:
            return render_to_response('vm_detail.html', 
                                      { 'form': form, 
                                       'vmHost': vmHost, 
                                       'vm': vm, 
                                       'error_message': form.errors, })
    else:
        form = VMForm()
        return render_to_response('vm_detail.html', { 'form': form, 'vmHost': vmHost, 'vm': vm, })

def VMEdit(request, VMHost_id, VM_id):
    vmHost = get_object_or_404(VMHOST, pk=VMHost_id)
    vm = get_object_or_404(VM, pk=VM_id)
    disks = vm.vmdisk_set.all()
    VMFormTmp = form_for_instance(vm)
    if request.method == 'POST':
        form = VMFormTmp(request.POST)
        if form.is_valid():
            vm = form.save()
            return HttpResponseRedirect('/ovim/' + VMHost_id + '/listvms/')
        else:
            return render_to_response('vm_detail.html', { 'form': form, 'vmHost': vmHost, 'vm': vm, 'disks': disks, 'error_message': form.errors, })
    else:
        form = VMFormTmp()
        return render_to_response('vm_detail.html', { 'form': form, 'vmHost': vmHost, 'vm': vm, 'disks': disks, } )

def VMHostList(request):
    vmhosts = VMHOST.objects.all()
    return render_to_response('vmhost_list.html', { 'object_list': vmhosts, })

def VMHostEdit(request, object_id):
    vmhost = get_object_or_404(VMHOST, pk=object_id)
    VMHOSTFormTmp = form_for_instance(vmhost)
    if request.method == 'POST':
        form = VMHOSTFormTmp(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/ovim')
        else:
            return render_to_response('vmhost_detail.html', { 'form': form, 'object': vmhost, 'error_message': form.errors, })
    else:
        form = VMHOSTFormTmp()
        return render_to_response('vmhost_detail.html', { 'form': form, 'object': vmhost, })

def VMHostAdd(request):
    form = VMHOSTForm()
    object = None
    if request.method == 'POST':
        form = VMHOSTForm(request.POST)
        if form.is_valid():
            object = VMHOST(**form.cleaned_data)
            object.save()
            return HttpResponseRedirect('/ovim')
        else:
            return render_to_response('vmhost_detail.html', 
                                      { 'form': form, 
                                       'object': object, 
                                       'error_message': form.errors, })
        
    else:
        form = VMHOSTForm()
        return render_to_response('vmhost_detail.html', { 'form': form, 'object': object, })
    

def VMHostDelete(request, object_id):
    object = get_object_or_404(VMHOST, pk=object_id)
    object.delete()
    return HttpResponseRedirect('/ovim')

def JPList(request):
    jps = BackupJobPool.objects.all()
    return render_to_response('jp_list.html', { 'jps': jps, })

def JPMonitor(request, jp_id):
    jp = get_object_or_404(BackupJobPool, pk=jp_id)
    vms = jp.vmlist.all()
    jbs = Jobs.objects.filter(joppool_id=jp.cur_taskid)
    return render_to_response('jp_monit.html', { 'jp': jp, 'vms': vms, 'jbs': jbs})

def JPDelete(request, jp_id):
    jp = get_object_or_404(BackupJobPool, pk=jp_id)
    jp.delete()
    return HttpResponseRedirect('/ovim/listjp/')

def RestartJP(request, jp_id):
    jp = get_object_or_404(BackupJobPool, pk=jp_id)
    jp.state = 'RDY'
    jp.lastrun = None
    jp.startdate = datetime.datetime.now()
    jp.save()
    return HttpResponseRedirect('/ovim/listjp/')

def JPEdit(request, jp_id):
    jp = get_object_or_404(BackupJobPool, pk=jp_id)
    JobPoolFormTmp = form_for_instance(jp, fields=('name', 'comments', 'backupmode', 'startat', 'startmethod', 'timeoutH', 'vmlist'))
    if request.method == 'POST':
        form = JobPoolFormTmp(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/ovim/listjp/')
        else:
            return render_to_response('jp_edit.html', { 'form': form, 'jp': jp, 'error_message': form.errors, })
    else:
        form = JobPoolFormTmp()
        return render_to_response('jp_edit.html', { 'form': form, 'jp': jp, })

def JPAdd(request):
    JobPoolFormTmp = form_for_model(BackupJobPool, fields=('name', 'comments', 'backupmode', 'startat', 'startmethod', 'timeoutH', 'vmlist'))
    if request.method == 'POST':
        form = JobPoolFormTmp(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/ovim/listjp/')
        else:
            return render_to_response('jp_edit.html', 
                                      { 'form': form, 
                                       'error_message': form.errors, })
        
    else:
        form = JobPoolFormTmp()
        return render_to_response('jp_edit.html', { 'form': form, })

def JBMonitor(request):
    jbs = Jobs.objects.all()
    jps = BackupJobPool.objects.all()
    return render_to_response('jbmonitor.html', { 'jbs': jbs, 'jps': jps,})

def Logview_core(request):
    les = Log.objects.filter(component='OVIMCore').order_by('date')[:100]
    jps = BackupJobPool.objects.all()
    return render_to_response('log_view.html', { 'les': les, 'jps': jps, })

def Logview_by_jobid(request, job_id):
    les = Log.objects.filter(jobid=job_id)
    jps = BackupJobPool.objects.all()
    return render_to_response('ajaxlog_view.html', { 'les': les, 'jps': jps, })

def Logview_by_component(request, cmpnt):
    les = Log.objects.filter(component=cmpnt)
    jps = BackupJobPool.objects.all()
    return render_to_response('log_view.html', { 'les': les, 'jps': jps, })

def OVIMSetup(request):
    if OVIMSettings.objects.count() == 0:
        setup = OVIMSettings()
        setup.save()
    else:
        setup = OVIMSettings.objects.all()[0]
        
    SetupForm = form_for_instance(setup)
    if request.method == 'POST':
        form = SetupForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/ovim/')
        else:
            return render_to_response('setup.html', 
                                      { 'form': form, 
                                       'error_message': form.errors, })
        
    else:
        form = SetupForm()
        return render_to_response('setup.html', { 'form': form})

def VMRecover(request, VMHost_id, VM_id):
    vm = get_object_or_404(VM, pk=VM_id)
    if request.method == 'POST':
        form = VMRecoverForm(request.POST)
        if form.is_valid():
            rj = Jobs()
            rj.vm = vm
            rj.type = 'RECOVER'
            rj.mode = 'HOT'
            rj.state = 'READY'
            rj.storage = LocalStorage.objects.get(id=form.data['from_store'])
            rj.save()
            return HttpResponseRedirect('/ovim/')
        else:
             return render_to_response('recover_vm.html', 
                                      { 'form': form, 
                                       'error_message': form.errors, })           
    else:
        form = VMRecoverForm()
        return render_to_response('recover_vm.html', { 'form': form, 'vm': vm, })
